<?php

namespace app\common\job;

use Sanyc\Aliyun\AliyunEmail;
use think\queue\Job;
use think\Exception;
use Carbon\Carbon;
use think\Loader;
use think\Request;

class Order 
{
    const ORDER_INITIAL_STAGE = 0;//订单初始阶段
    const ORDER_PAYMENT_STAGE = 1;//订单支付阶段
    const ORDER_REFUND_STAGE  = 2;//订单退款阶段
    const ORDER_COMPLETION    = 3;//订单完成
    const ORDER_CANCEL_STAGE  = 4;//订单取消
    const MAX_DIFF_DAYS       = 7;
    const START_STATE         = 0;//阶段开始
    const STATE_END           = 1;//阶段结束
    const FAIL                = -1;//阶段失败

    public function unLock(Job $job, $data)
    {
        $send_notice = false;
        try {
            Request::instance()->module('common');
            $order_info  = Loader::model('Orders')->getOrderInfo(['number' => $data]);
            $order_stage = $order_info->getData('stage');
            if ($order_stage == self::ORDER_COMPLETION || $order_stage == self::ORDER_CANCEL_STAGE || $order_stage == self::ORDER_REFUND_STAGE) {
                $job->delete();
            }else{
                $order_info->cancelOrder('订单超时');
                $send_notice = true;
            }

        } catch (\Exception $e) {
            return false;
        }

        if ($send_notice) {
            try {
                $notice_instance = \services\notices\Notice::instance();
                $user_info       = $this->getUserInfo($order_info->order_user_id);
                if ($user_info->email) {
                    $recipients['mail'] = $user_info->email;
                }

                $recipients['sign'] = $user_info->sign;

                $notice_instance->send($recipients, '订单超时', '订单长时间未支付已被被取消');
            } catch (Exception $e) {}
        }
        $job->delete();     
    }

    protected function getUserInfo($user_id)
    {
        return Loader::model('common/Users')->getUserInfo($user_id);
    }

}